package com.jdk.demo.thread.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAdder;

public class LongAdderDemo {

	private static final int MAX_THREADS = 3;
    private static final int TASK_COUNT = 3;
    private LongAdder lacount = new LongAdder();
    private static CountDownLatch cdladdr = new CountDownLatch(TASK_COUNT);

	public static void main(String[] args) throws InterruptedException {
		LongAdderDemo demo = new LongAdderDemo();
		demo.testLongAdder();
	}

	public void testLongAdder() throws InterruptedException {
        ExecutorService exe = Executors.newFixedThreadPool(MAX_THREADS);
        LongAdderThread atomic = new LongAdderThread();
        for (int i = 0; i < TASK_COUNT; i++) {
            exe.submit(atomic);
        }
        cdladdr.await();
        System.out.println("v=" + lacount.sum());
        exe.shutdown();
    }

	public class LongAdderThread implements Runnable {

        @Override
        public void run() {
            for (int i=0; i<100; i++) {
                lacount.add(1L);
                System.out.println(Thread.currentThread().getName() + ": " + lacount);
            }
            cdladdr.countDown();
        }

    }

}
